<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ChatRoom</title>
    <script type="text/javascript" src="../js/jquery.min.js"></script>
</head>
<body>
<div id="login">
<form id="loginForm"  >
    用户名: <input name="username">
    <br>
    <input type="button" value="登录" onclick="login()" />
</form>
</div>
<textarea id="msg" placeholder=""  style="width: 500px;height: 50px" ></textarea>
<input type="button" onclick="send()" value="发送消息"  >
<br>
<textarea id="history"   style="width: 500px;height: 200px ; max-lines: 10" >
</textarea>


<script type="text/javascript">
    var socket ;
    //登录过后初始化socket连接
    function initSocket(username) {
        if(typeof(WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
        }else {
            console.log("您的浏览器支持WebSocket/websocket");
        }
        //socket连接地址: 注意是ws协议
        socket = new WebSocket("ws://"+location.host+"/web/websocket/chat");
        socket.onopen = function() {
            console.log("Socket 已打开");
        };
        //获得消息事件
        socket.onmessage = function(msg) {
            var history = $("#history").val();
            $("#history").val(history+"\r\n"+msg.data);
            console.log($(msg));
        };
        //关闭事件

        socket.onclose = function() {
            console.log("Socket已关闭");
        };
        //错误事件
        socket.onerror = function() {
            alert("Socket发生了错误");
        }
    }
    //点击按钮发送消息
    function send() {
        console.log("发送消息: "+$("#msg").val());
        socket.send($("#msg").val());
    }
    //登录
    function login() {
        $.ajax({
            url: "/web/websocket/login",
            data: $("#loginForm").serialize(),
            type: "POST",
            success: function (username) {
                if ( username){
                    console.log("登录成功!");
                    $("#login").hide();
                    initSocket(username);
                }
            }
        });
    }
</script>
</body>
</html>